package gaff.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.crypto.MacProvider;

import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


public class JWT {
    /*
        http://www.jianshu.com/p/6307c89fe3fa
     */
    public static void f1() {
        Map<String, Object> claims = new HashMap();
        claims.put("username", "yong");
        String secret = "pp123";
        String token = Jwts.builder()
                .setClaims(claims)
                .setExpiration(new Date(1498039445886L))
                .signWith(SignatureAlgorithm.HS512, secret) //采用什么算法是可以自己选择的，不一定非要采用HS512
                .compact();
        System.out.println(token);
        Claims claims2 = getClaimsFromToken(token);
        System.out.println(claims2);
    }

    public static Claims getClaimsFromToken(String token) {
        Claims claims;
        try {
            String secret = "pp129"; // why also got the claims?
            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            claims = null;
        }
        return claims;
    }

    public static void main(String[] args) {
//        f1();

        // We need a signing key, so we'll create one just for this example. Usually
        // the key would be read from your application configuration instead.
        Key key = MacProvider.generateKey();
        Key key2 = MacProvider.generateKey();

        String compactJws = Jwts.builder()
                .setSubject("Joe")
                .signWith(SignatureAlgorithm.HS512, key)
                .compact();
        System.out.println(compactJws);
        compactJws = Jwts.builder()
                .setSubject("Joe")
                .signWith(SignatureAlgorithm.HS512, key2)
                .compact();
        System.out.println(compactJws);

        System.out.println(Jwts.parser().setSigningKey(key2).parseClaimsJws(compactJws).getBody().getSubject());
        assert Jwts.parser().setSigningKey(key2).parseClaimsJws(compactJws).getBody().getSubject().equals("Joe");


    }
}
